import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2020/7/3.
 */
import React, { Component, PropTypes } from "react";
import { messages, queryCurrencyPrecision, eventTrack } from 'share/common'
import { connect } from 'react-redux';
import moment from 'moment'
import requestService from 'containers/request/request.service'
import baseService from 'share/base.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import 'styles/request/new-request/expense-type-modal.scss'
import { Button, Row, Col, Icon,  Checkbox, message, Popconfirm, Spin, Modal, Divider, Tag } from 'antd'
import Condition from 'components/condition';
const If = Condition.If;
import travelUtil from 'containers/request/travel-request/travelUtil'
import requestUtil from 'containers/request/slide/request-util'
import TravelLocation from 'containers/request/travel-request/comp/location'
import ExpenseTypeSelector from 'components/template/expense-type-selector'
const CheckboxGroup = Checkbox.Group;
import debounce from 'lodash.debounce'
import TravelBookBtn from 'containers/request/travel-request/travel-book-btn'
import TravelOrderList from 'containers/request/travel-request/travel-order-list'
import ItineraryBudgetShow from 'containers/request/slide/content/itinerary-budget-show'
import SlideFrame from 'components/slide-frame'
import originalImgZH from 'images/travel/original.png';
import originalImgEN from 'images/travel/original-en.png';

class RequestItineraryList extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      itineraryHeadList: [], //行程头列表
      editObj: {
        isEdit: false // 是否正在编辑某个行程头
      },
      modalVisible: false,
      selectedExpense: {},
      expenseItinerary: {}, //标记在哪个行程下操作明细
    };
  }

  componentDidMount() {
    this.setState({itineraryHeadList: this.props.itineraryHeadList});
  }

  componentWillReceiveProps(nextProps) {
    this.setState({itineraryHeadList: nextProps.itineraryHeadList});
  }

  getItineraryHead = () => {
    const { onChange } = this.props;
    const { info } = this.context;
    if (info.applicationOID) {
      this.setState({loading: true});
      requestService.getItineraryHead(info.applicationOID, true).then(res => {
        this.setState({itineraryHeadList: res.data, loading: false});
        onChange(res.data);
      }).catch(err => {
        this.setState({loading: false});
        errorMessage(err.response);
      });
    }
  };

  handleDelete = (e, itineraryHeadId) => {
    eventTrack({
      category: '行程编辑',
      action: '删除'
    });
    const { refreshInfo } = this.context;
    this.setState({loading: true});
    requestService.removeItinerary(itineraryHeadId).then(res => {
      this.setState({loading: false});
      refreshInfo();
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  handleDeleteBudget = (applicationCustomBudgetId) => {
    eventTrack({
      category: '行程明细新建/编辑',
      action: '明细列表单行删除次数'
    });
    const { refreshInfo } = this.context;
    this.setState({loading: true});
    requestService.removeItineraryBudget(applicationCustomBudgetId).then(res => {
      this.setState({loading: false});
      refreshInfo();
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  handleEdit = (index) => {
    eventTrack({
      category: '行程编辑',
      action: '编辑'
    });
    const { onToggleEdit } = this.props;
    const { itineraryHeadList } = this.state;
    this.setState({editObj: {
      isEdit: true,
      ...itineraryHeadList[index]
    }});
    onToggleEdit(true);
  };

  handleChangeEditObjValue = (value, key) => {
    let { editObj } = this.state;
    if (key === 'fromCity' || key === 'toCity') {
      editObj[`${key}Name`] = value.adName;
      editObj[`${key}Code`] = value.adCode;
    } else {
      editObj[key] = value;
    }
    this.setState({editObj});
  };

  handleCancelEditObj = () => {
    const { onToggleEdit } = this.props;
    this.setState({editObj: {isEdit: false}});
    onToggleEdit(false);
  };

  handleSaveEditObj = (clearSubsidies) => {
    const { onToggleEdit } = this.props;
    const { editObj } = this.state;
    const { refreshInfo } = this.context;
    if (requestUtil.validateHead(false, [editObj])) {
      let params = requestUtil.processHeadParams([editObj]);
      this.setState({loading: true});
      requestService.saveItineraryHead(params && params[0], clearSubsidies).then(res => {
        this.setState({editObj: {isEdit: false}});
        onToggleEdit(false);
        refreshInfo();
      }).catch(err => {
        this.setState({loading: false});
        errorMessage(err.response);
      });
    }
  };

  /**
   * 控制添加费用类型弹框
   * @param isOpen 弹框的展示
   * @param isAddBudget 确定btn的回调，是否要打开添加费用控件，分摊界面
   * @param index 在哪个行程头下添加明细
   */
  showExpenseModal = (isOpen, isAddBudget, index) => {
    const { onAddBudget } = this.props;
    const { itineraryHeadList } = this.state;
    if (isOpen) {
      eventTrack({
        category: '行程编辑',
        action: '添加明细'
      });
      this.setState({selectedExpense: {}});
    }
    if (index !== undefined) {
      this.setState({
        expenseItinerary: itineraryHeadList[index]
      });
    }
    this.setState({modalVisible: isOpen}, () => {
      if (isAddBudget && onAddBudget) {
        onAddBudget(this.state.selectedExpense, this.state.expenseItinerary);
      }
    });
  };

  getExpenseParams = () =>{
    const { form, jobInfo, info } = this.context;
    const { user } = this.props;
    if (form && form.formOID) {
      let companyOID = travelUtil.getFormHeadValue(info.custFormValues, 'select_company') || jobInfo.companyOID || user.companyOID;
      return {
        companyOID,
        formOID: form.formOID,
        subsidyType: 0,
        userOID: user.userOID,
        setOfBooksId: form.setOfBooksId
      };
    } else {
      return {};
    }
  };

  handleSelectExpenseType = (value) => {
    this.setState({selectedExpense: value});
  };

  //非编辑状态打开侧滑展示行程明细
  onShowBudget = (budget) => {
    eventTrack({
      category: '申请单提交后',
      action: '行程明细行点击次数'
    });
    const { applicant } = this.context;
    SlideFrame.open({
      title: messages('request-1.key271')/*行程明细*/,
      content: ItineraryBudgetShow,
      afterClose: this.handleCloseSlide,
      params: {
        budget,
        applicant
      }
    }, this);
  };

  handleCloseSlide = () => {};

  handleModalConfirm = (e, itineraryHeadId, type) => {
    e.preventDefault();
    e.stopPropagation();
    let message = messages('request-1.key390')/*重新编辑行程将影响差补计算，继续将为您清空所有差补*/;
    if (type === 'delete') {
      message = messages('request-1.key391')/*删除行程将影响差补计算，继续将为您清空所有差补*/;
    }
    Modal.confirm({
      title: messages('common.info')/*提示*/,
      content: <div>
        <p>{message}</p>
      </div>,
      okText: messages('request-1.key392')/*继续*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        if (type === 'delete') {
          this.handleDelete(e, itineraryHeadId);
        }
        if (type === 'edit') {
          this.handleSaveEditObj(true);
        }
      },
      onCancel: () => {}
    });
  };

  toggleShowContent = (index) => {
    let { itineraryHeadList } = this.state;
    if (itineraryHeadList[index].isOpen) {
      eventTrack({
        category: '申请单提交后',
        action: '行程头收起'
      });
    } else {
      eventTrack({
        category: '申请单提交后',
        action: '行程头展开'
      });
    }
    itineraryHeadList[index].isOpen = !itineraryHeadList[index].isOpen;
    this.setState({itineraryHeadList});
  };

  render() {
    const { itineraryHeadList, loading, editObj, modalVisible, selectedExpense } = this.state;
    const { info } = this.context;
    const { onEditBudget, disabled, isCollapsed, disabledList, isReadOnly } = this.props;
    return (
      <div className="itinerary-list">
        <Spin spinning={loading}>
          {itineraryHeadList.map((itinerary, index) => {
            let isHasSubsidy = requestUtil.isHasSubsidy([itinerary]);
            return (
              <div className="itinerary-item" key={itinerary.itineraryHeadId}>
                <div className="itinerary-item-title">
                  <If value={editObj.itineraryHeadId !== itinerary.itineraryHeadId}>
                    <div className="font-no">{messages('request-1.key290')/*行程*/}{index + 1}</div>
                    <div className="font-title">{itinerary.fromCityName}&nbsp;-&nbsp;{itinerary.toCityName}</div>
                    <div className="font-sub">
                      {moment(itinerary.startDate).format('YYYY-MM-DD')}
                      &nbsp;~&nbsp;
                      {moment(itinerary.endDate).format('YYYY-MM-DD')}，
                      {messages('request-1.key384',{arg1: travelUtil.calculateDate(itinerary.startDate,itinerary.endDate)})/*共{arg1}天*/}
                    </div>
                    <If value={!editObj.isEdit && !disabled && !disabledList}>
                      <div className="operation-block">
                        <If value={!itinerary.isExtend}>
                          <span className="icon-btn" onClick={() => this.handleEdit(index)}>
                            <Icon type="edit" />&nbsp;{messages('common.edit')/*编辑*/}
                          </span>
                        </If>
                        <span className="icon-btn">
                          <Popconfirm onConfirm={(e) => this.handleDelete(e, itinerary.itineraryHeadId)} title={messages('request-1.key393')/*确定删除行程吗？*/}>
                            <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}><Icon type="delete" />&nbsp;{messages('common.delete')/*删除*/}</a>
                          </Popconfirm>
                        </span>
                      </div>
                    </If>
                    <div>
                      <If value={!!itinerary.baseCurrencyAmount}>
                        <span className="currency-amount">
                          {info.currencyCode}&nbsp;
                          {React.Component.prototype.filterMoney(itinerary.baseCurrencyAmount, queryCurrencyPrecision(info.currencyCode), true)}
                        </span>
                        <Divider type="vertical" style={{margin: '0 0', color: '#BFC4D1'}} />
                      </If>
                      <If value={disabled && itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.length}>
                        <span className="icon-btn" onClick={() => this.toggleShowContent(index)}>
                          <If value={itinerary.isOpen}>
                            {messages('common.fold')/*收起*/}&nbsp;<Icon type="up" />
                          </If>
                          <If value={!itinerary.isOpen}>
                            {messages('request-1.key853')/*展开*/}&nbsp;<Icon type="down" />
                          </If>
                        </span>
                      </If>
                      <If value={!editObj.isEdit && !disabled && !disabledList}>
                        <span
                          className="icon-btn"
                          style={!!itinerary.baseCurrencyAmount ? {} : {marginLeft: 0}}
                          onClick={() => this.showExpenseModal(true, false, index)}
                        >
                          <Icon type="plus" />&nbsp;{messages('request-1.key394')/*添加明细*/}
                        </span>
                      </If>
                    </div>
                  </If>
                  <If value={editObj.itineraryHeadId === itinerary.itineraryHeadId}>
                    <div className="font-no">{messages('request-1.key290')/*行程*/}{index + 1}</div>
                    <div className="edit-itinerary-content">
                      <Row type="flex" align="middle" gutter={16} className="list-header">
                        <Col span={12}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              {messages('request-1.key85')/*出发地*/}
                            </Col>
                            <Col span={11} offset={2}>
                              {messages('request-1.key395')/*目的地*/}
                            </Col>
                          </Row>
                        </Col>
                        <Col span={12}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              {messages('request-1.key396')/*开始日期*/}
                            </Col>
                            <Col span={11} offset={2}>
                              {messages('request-1.key397')/*离开日期*/}
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                      <Row type="flex" align="middle" gutter={16} style={{marginBottom: 16}}>
                        <Col span={12}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              <TravelLocation
                                placeHolder={messages('request-1.key85')/*出发地*/}
                                value={{
                                  adCode: editObj.fromCityCode,
                                  adName: editObj.fromCityName
                                }}
                                onSelect={cityObj => this.handleChangeEditObjValue(cityObj, 'fromCity')}
                              />
                            </Col>
                            <Col span={2} className="content-gap">—</Col>
                            <Col span={11}>
                              <TravelLocation
                                placeHolder={messages('request-1.key395')/*目的地*/}
                                value={{
                                  adCode: editObj.toCityCode,
                                  adName: editObj.toCityName
                                }}
                                onSelect={cityObj => this.handleChangeEditObjValue(cityObj, 'toCity')}
                              />
                            </Col>
                          </Row>
                        </Col>
                        <Col span={12}>
                          <Row type="flex" align="middle">
                            <Col span={11}>
                              <DatePicker
                                placeholder={messages('request-1.key396')/*开始日期*/}
                                style={{width: '100%'}}
                                allowClear={false}
                                value={moment(editObj.startDate)}
                                onChange={value => this.handleChangeEditObjValue(value, 'startDate')}
                                disabledDate={c=> requestUtil.disabledDate(c, info && info.custFormValues)}
                              />
                            </Col>
                            <Col span={2} className="content-gap">—</Col>
                            <Col span={11}>
                              <DatePicker
                                placeholder={messages('request-1.key397')/*离开日期*/}
                                style={{width: '100%'}}
                                allowClear={false}
                                value={moment(editObj.endDate)}
                                onChange={value => this.handleChangeEditObjValue(value, 'endDate')}
                                disabledDate={c=> requestUtil.disabledDate(c, info && info.custFormValues)}
                              />
                            </Col>
                          </Row>
                        </Col>
                      </Row>
                      <Row type="flex" align="middle">
                        <Col span={20}>
                          <If value={isHasSubsidy && requestUtil.isChangeHead(itinerary, editObj)}>
                            <Button type="primary" style={{marginRight: 8}} onClick={(e) => this.handleModalConfirm(e, null, 'edit')}>{messages('common.save')/*保存*/}</Button>
                          </If>
                          <If value={!isHasSubsidy || !requestUtil.isChangeHead(itinerary, editObj)}>
                            <Button type="primary" style={{marginRight: 8}} onClick={e => this.handleSaveEditObj()}>{messages('common.save')/*保存*/}</Button>
                          </If>
                          <Button onClick={this.handleCancelEditObj}>{messages('common.cancel')/*取消*/}</Button>
                        </Col>
                      </Row>
                    </div>
                  </If>
                </div>
                <If value={itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.length}>
                  <div className={`itinerary-item-content ${((disabled && itinerary.isOpen) || !disabled) ? '' : 'itinerary-closed'}`}>
                    {itinerary.itineraryBudgetDTOList && itinerary.itineraryBudgetDTOList.map((itineraryBudget, itineraryIndex) => {
                      let { isHas, type, orderList, orderItinerary } = requestUtil.isHasOrder(itineraryBudget);
                      return (
                        <div key={itineraryBudget.applicationCustomBudgetId}>
                          <div className="budget-item" onClick={disabled ? () => this.onShowBudget(itineraryBudget) : () => onEditBudget(itineraryBudget.applicationCustomBudgetId)}>
                            <If value={itineraryBudget.isExtend}>
                              <img className="original-img" src={messages('request-1.key513')/*ZH*/ === 'EN' ? originalImgEN : originalImgZH}/>
                            </If>
                            <Row type="flex" align="middle">
                              <Col span={20}>
                                <Row type="flex" align="middle" style={{lineHeight: '28px'}}>
                                  <img src={itineraryBudget.expenseTypeIconURL} className="icon-img"/>
                                  <span className="budget-title">{itineraryBudget.expenseTypeName}</span>
                                  <If value={!!requestUtil.getCompanyPaidStr(itineraryBudget.expenseBudgetCustomValueDTOs)}>
                                    <Tag color="#F3F7FE" style={{color: '#4B8DFF', marginLeft: 8}}>
                                      {requestUtil.getCompanyPaidStr(itineraryBudget.expenseBudgetCustomValueDTOs)}
                                    </Tag>
                                  </If>
                                </Row>
                                <If value={!!requestUtil.getAmountStr(itineraryBudget.expenseBudgetCustomValueDTOs, itineraryBudget)}>
                                  <Row type="flex" align="middle" style={{paddingLeft: 44}}>
                                    <span className="budget-amount">
                                      {info.currencyCode}：{React.Component.prototype.filterMoney(itineraryBudget.baseCurrencyAmount, queryCurrencyPrecision(info.currencyCode), true)}
                                    </span>
                                    <span className="sub-budget-amount">
                                      &nbsp;&nbsp;&nbsp;
                                      {requestUtil.getAmountStr(itineraryBudget.expenseBudgetCustomValueDTOs, itineraryBudget)}
                                      &nbsp;|&nbsp;{messages('common.currency.rate')/*汇率*/}：{itineraryBudget.companyCurrencyRate.toFixed(7)}
                                    </span>
                                  </Row>
                                </If>
                                <If value={disabled && (requestUtil.getUniformStr(itineraryBudget, info) || itineraryBudget.approvalNumber)}>
                                  <div style={{paddingLeft: 44, color: '#4E5B71'}}>
                                    {requestUtil.getUniformStr(itineraryBudget, info)}
                                    {requestUtil.getUniformStr(itineraryBudget, info) && (<span>&nbsp;&nbsp;&nbsp;</span>)}
                                    {itineraryBudget.approvalNumber && (
                                      <span>{messages('request-1.key398')/*行程单号：*/}{itineraryBudget.approvalNumber}</span>
                                    )}
                                  </div>
                                </If>
                              </Col>
                              <If value={disabled && !isReadOnly}>
                                <Col span={4} style={{textAlign: 'right'}}>
                                  <TravelBookBtn itinerary={orderItinerary} type={type}/>
                                </Col>
                              </If>
                              <If value={!disabled && !editObj.isEdit && !disabledList}>
                                <Col span={4} style={{textAlign: 'right'}}>
                                  <Popconfirm onConfirm={() => this.handleDeleteBudget(itineraryBudget.applicationCustomBudgetId)} title={messages('request-1.key386')/*你确认要删除？*/}>
                                    <Button
                                      style={{width: 16, height: 16, minWidth: 16, fontSize: '12px'}}
                                      size="small"
                                      shape="circle"
                                      icon="close"
                                      className="budget-remove-icon"
                                      onClick={(e) => {e.preventDefault();e.stopPropagation();}}
                                    />
                                  </Popconfirm>
                                </Col>
                              </If>
                            </Row>
                            <If value={disabled && isHas}>
                              <TravelOrderList orderList={orderList} type={type} itinerary={orderItinerary} responsive isCollapsed={isCollapsed}/>
                            </If>
                          </div>
                          <If value={itineraryIndex < itinerary.itineraryBudgetDTOList.length - 1}>
                            <Divider style={{margin: '0 0', position: 'initial'}}/>
                          </If>
                        </div>
                      )
                    })}
                  </div>
                </If>
              </div>
            )
          })}
        </Spin>
        <Modal
          title={messages('request-1.key325')/*添加费用类型及金额*/}
          wrapClassName="expense-type-modal"
          width={860}
          footer={
            <div>
              <Button onClick={() => this.showExpenseModal(false)}>{messages('common.cancel')/*取消*/}</Button>
              <Button type="primary" disabled={!selectedExpense.id} onClick={() => this.showExpenseModal(false, true)}>{messages('common.ok')/*确定*/}</Button>
            </div>
          }
          visible={modalVisible}
          onCancel={() => this.showExpenseModal(false)}
        >
          <div className="expense-type-container">
            <ExpenseTypeSelector
              onSelect={this.handleSelectExpenseType}
              source="formV3"
              param={this.getExpenseParams()}
              value={selectedExpense}
            />
          </div>
        </Modal>
      </div>
    )
  }
}

RequestItineraryList.propTypes = {
  itineraryHeadList: PropTypes.array,
  onChange: PropTypes.func,
  onAddBudget: PropTypes.func,
  onEditBudget: PropTypes.func,
  onToggleEdit: PropTypes.func, //告诉父组件列表是否处于编辑状态
  disabled: PropTypes.bool, //是否是非编辑状态的差旅单，只能操作预订，目前没更改，所以没有停用行程
  disabledList: PropTypes.bool, //新建行程头的时候，产品认为需要列表不可操作
  isCollapsed: PropTypes.bool,
  isReadOnly: React.PropTypes.bool, //是否是只读状态，不展示预订按钮
};

RequestItineraryList.contextTypes = {
  applicant: PropTypes.object,
  form: PropTypes.object,
  info: PropTypes.object,
  jobInfo: PropTypes.object,
  refreshInfo: PropTypes.func,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
  }
}

export default connect(mapStateToProps)(RequestItineraryList)
